package cn.cloud9.opencloud.common.security;

import cn.cloud9.opencloud.common.annotation.LoginCheckPassed;
import cn.cloud9.opencloud.common.api.Result;
import cn.cloud9.opencloud.common.api.ResultMessage;
import cn.cloud9.opencloud.common.util.EmptyUtil;
import cn.cloud9.opencloud.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月17日 6:50
 */
public abstract class AbstractSecurityCheckInterceptor extends HandlerInterceptorAdapter {
    protected Logger _logger = LoggerFactory.getLogger(getClass());

    @Value("${system.code:common}")
    protected String systemCode;

    @Value("${security.check-request-ip:true}")
    protected boolean checkRequestIp;

    public AbstractSecurityCheckInterceptor() {}

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 标记了 忽略登陆注解的接口直接放行
        final boolean assignable = handler.getClass().isAssignableFrom(HandlerMethod.class);
        LoginCheckPassed loginCheckPassed = assignable ?
                ( (HandlerMethod) handler).getMethodAnnotation(LoginCheckPassed.class) : null;
        if (null != loginCheckPassed) return true;

        // 从请求头中获取令牌，如果令牌在头里面拿不到，就从GET请求参数中拿
        String token = request.getHeader("token");
        if (EmptyUtil.isEmptyString(token)) token = request.getParameter("token");

        // 请求这两个地方都拿不到token，直接判断为空
        if (EmptyUtil.isEmptyString(token)) {
            _logger.debug("token为空，请在requestHeader或者requestParam中添加token！");
            final Result<Object> result = Result.getInstance().error(ResultMessage.UNAUTHORIZED);
            WebUtil.sendJson(response, result);
            return false;
        }

        // 拿取IP
        if (this.checkRequestIp) {
            String ip = WebUtil.getRequestIp(request);
        }





        return false;
    }



}
